package org.spamforces.web.page;

import com.google.inject.Inject;
import org.nocturne.annotation.Action;
import org.nocturne.annotation.Parameter;
import org.nocturne.annotation.Validate;
import org.nocturne.link.Link;
import org.nocturne.util.StringUtil;
import org.nocturne.validation.ValidationException;
import org.nocturne.validation.Validator;
import org.spamforces.dao.UserDao;
import org.spamforces.model.User;

/**
 * @author MikeMirzayanov (mirzayanovmr@gmail.com)
 */
@Link(";login")
public class LoginPage extends WebPage {
    @Parameter(stripMode = Parameter.StripMode.SAFE)
    private String email;

    @Parameter(stripMode = Parameter.StripMode.NONE)
    private String password;

    @Inject
    private UserDao userDao;

    private User userForLogin;

    @Validate("enter")
    public boolean validateEnter() {
        addValidator("email", new Validator() {
            @Override
            public void run(String value) throws ValidationException {
                if (StringUtil.isEmptyOrNull(value) || !value.matches(".+@.+")) {
                    throw new ValidationException($("Enter valid email"));
                }
            }
        });

        addValidator("password", new Validator() {
            @Override
            public void run(String value) throws ValidationException {
                userForLogin = userDao.authenticate(email, password);

                if (userForLogin == null) {
                    throw new ValidationException(
                            $("Invalid login or password"));
                }
            }
        });
        return runValidation();
    }

    @Action("enter")
    public void onLogin() {
        putSession(AUTHORIZED_USER_SESSION_KEY, userForLogin);
        abortWithRedirect(DashboardPage.class);
    }

    @Override
    public String getTitle() {
        return $("Enter");
    }

    @Override
    public void action() {
        // No operations.
    }

    @Override
    public boolean isAnonymousAccessAllowed() {
        return true;
    }
}
